package com.hy.dbrw;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by shitou on 17/12/24.
 */
@Component
public class DataSourceAspect {
    @Autowired
    private ApplicationContext ctx;

    public void before(JoinPoint point) {
        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?>[] classz = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        try {
            Method methodRefRes = classz[0].getMethod(method, parameterTypes);
            if (methodRefRes != null && methodRefRes.isAnnotationPresent(DataSource.class)) {
                DataSource data = methodRefRes.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
            }else {
                DynamicDataSourceHolder.putDataSource("default");
            }
        } catch (Exception e) {
            DynamicDataSourceHolder.putDataSource("default");
            System.out.println("数据源失败切面获取异常:" + e.getMessage());
        }
    }
}
